package com.kuang.demo02;

/**不安全案例，买票
 * @author FHL
 */
public class UnsafeBuyTicket implements Runnable{
    private  int ticketNumber=10;
    //设置外部停止方式
    boolean flag=true;
    public static void main(String[] args) {
UnsafeBuyTicket buyTicket=new UnsafeBuyTicket();
new Thread(buyTicket,"1号买家").start();
new Thread(buyTicket,"2号买家").start();
new Thread(buyTicket,"3号买家").start();
    }

    @Override
    public void run() {
        //买票
        while (flag){
            buy();
        }
    }
    //synchronized:同步，保证线程安全
    public synchronized void  buy(){
        //判断是否还有票
        if (ticketNumber<=0){
            flag=false;
            return;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"成功买到"+ticketNumber--);
    }
}
